import React, { useEffect, useRef } from 'react'
import {
  Form,
  Input,
  Button,
  Radio,
  Toast,
  NavBar
} from 'antd-mobile'
import axios from 'axios'
import { connect } from 'react-redux';
import getCenterList from '../../redux/createActor/getCenterList';
import { useNavigate } from 'react-router-dom';

function Changecenter(props) { 
  const navigate = useNavigate();
  let { personalList, getCenterList} = props;
  const ref = useRef();
  useEffect(()=>{
    if(personalList.length === 0){
      getCenterList();
    }
    else{
      ref.current.setFieldsValue({
        username: personalList[0].username,
        gender: personalList[0].gender,
        address: personalList[0].address,
        national: personalList[0].country,
        city: personalList[0].city,
        tel: personalList[0].tel
    })
    }
  },[personalList, getCenterList])
  const onFinish = (values) => {
    console.log(values);
    Toast.show("个人信息修改成功")
    axios.patch(`/users/${personalList[0].id}`,{
        gender: values.gender,
        address: values.address,
        country: values.national,
        city: values.city,
        tel: values.tel
    })
      window.location.reload();
  }
  return (
    <div style={{paddingBottom:'3.0625rem'}}>
      <NavBar onBack={()=>{
        navigate('/auth/center')
      }}>修改个人信息</NavBar>
      <Form
        layout='horizontal'
        onFinish={onFinish}
        ref = {ref}
        footer={
          <Button 
            block 
            type='submit' 
            color='primary' 
            size='large'
           >
            提交
          </Button>
        }
      >
        <Form.Item
          name='username'
          label='昵称'
          disabled
        >
          <Input placeholder='' />
        </Form.Item>
        <Form.Item 
            name='gender' 
            label='性别'
            rules={[{ required: true, message: '必须选一个性别' }]}
        >
            <Radio.Group>
                <Radio value='0'>男&emsp;</Radio>
                <Radio value='1'>女&emsp;</Radio>
                <Radio value='2'>第三性别</Radio>
            </Radio.Group>
        </Form.Item>
        <Form.Item name='national' label='国籍' help='所属国家'>
          <Input placeholder='请输入国家' />
        </Form.Item>
        <Form.Item name='city' label='城市' help='居住城市'>
          <Input placeholder='请输入城市' />
        </Form.Item>
        <Form.Item name='address' label='地址' help='详情地址'>
          <Input placeholder='请输入地址' />
        </Form.Item>
        <Form.Item 
            name='tel' 
            label='电话'
            rules={[{ min:11, max:11, message: '电话是11位数字哦~' }]}
        >
          <Input type='number' placeholder='输入你的电话，11位数字' />
        </Form.Item>
      </Form>
    </div>
  )
}

const mapStateToProps = (state) =>{
  return {
    personalList: state.centerReducer.personalList
  }
}

const mapDispatchToProps = {
  getCenterList,
}

export default connect(mapStateToProps, mapDispatchToProps)(Changecenter);